package com.kob.backend.service.impl.record;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kob.backend.mapper.RecordMapper;
import com.kob.backend.mapper.UserMapper;
import com.kob.backend.pojo.Record;
import com.kob.backend.pojo.User;
import com.kob.backend.service.record.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

@Service
public class RecordServiceImpl implements RecordService {

    @Autowired
    private RecordMapper recordMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public JSONObject getRecordList(Integer page,String select,Integer userId) {
        IPage<Record> recordPage = new Page<>(page, 8); //分页，一页10条记录
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        if("personalRecord".equals(select)) {
            queryWrapper.orderByDesc("id"); // 根据id排序
            queryWrapper.eq("a_id", userId).or().eq("b_id", userId);
        }else if("allRecord".equals(select)){
            queryWrapper.orderByDesc("id");
        }
        //返回recordPage页的10条记录并根据id排序
        List<Record> records = recordMapper.selectPage(recordPage, queryWrapper).getRecords();
        JSONObject resp = new JSONObject();
        List<JSONObject> items = new LinkedList<>();
        for (Record record : records) {
            User userA = userMapper.selectById(record.getAId());
            User userB = userMapper.selectById(record.getBId());
            String loser = record.getLoser();
            String result = "平局";
            if("A".equals(loser)){
                result = "玩家B胜";
            }else if("B".equals(loser)){
                result = "玩家A胜";
            }
            JSONObject item = new JSONObject();
            item.put("a_username",userA.getUsername());
            item.put("a_photo",userA.getPhoto());
            item.put("b_username",userB.getUsername());
            item.put("b_photo",userB.getPhoto());
            item.put("result",result);
            item.put("record",record);
            items.add(item);
        }
        resp.put("records",items);
        QueryWrapper<Record> recordQueryWrapper = new QueryWrapper<>();
        if("personalRecord".equals(select))
            recordQueryWrapper.eq("a_id", userId).or().eq("b_id", userId);
        resp.put("records_count",recordMapper.selectCount(recordQueryWrapper));
        return resp;
    }
}
